#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    int height(TreeNode* node)
    {
        if (node == nullptr) return 0;
        int left_length = height(node->left);
        if (left_length == -1) return -1;
        int right_length = height(node->right);
        if (right_length == -1 || abs(left_length - right_length) > 1) return -1;

        return max(left_length, right_length) + 1;
    }
public:
    bool isBalanced(TreeNode* root) {
        int length = height(root);
        return length != -1;
    }
};